<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-wrapper" shadow="never">
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="领料单编号" prop="requisitionNo">
          <el-input v-model="queryParams.requisitionNo" placeholder="请输入领料单编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="领料单名称" prop="requisitionName">
          <el-input v-model="queryParams.requisitionName" placeholder="请输入领料单名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="生产工单" prop="workOrderNo">
          <el-input v-model="queryParams.workOrderNo" placeholder="请输入生产工单" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="工作站" prop="workstation">
          <el-input v-model="queryParams.workstation" placeholder="请输入工作站" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="客户编号" prop="customerCode">
          <el-input v-model="queryParams.customerCode" placeholder="请输入客户编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-wrapper" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="left">
            <el-button type="primary" :icon="Plus" @click="handleAdd">新增领料单</el-button>
          </div>
          <div class="right">
            <el-tooltip content="刷新" placement="top">
              <el-button :icon="Refresh" circle @click="getList" />
            </el-tooltip>
          </div>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="materialReceiptCode" label="领料单编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="materialReceiptName" label="领料单名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="demandTime" label="需求时间" min-width="120" show-overflow-tooltip />
        <el-table-column prop="workOrder" label="生产工单" min-width="120" show-overflow-tooltip />
        <el-table-column prop="workstation" label="工作站" min-width="120" show-overflow-tooltip />
        <el-table-column prop="workstationName" label="工作站名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="clientCode" label="客户编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="clientName" label="客户名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="descs" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.pageIndex"
          v-model:page-size="page.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="page.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="dialog-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="领料单编号" prop="materialReceiptCode">
              <el-input v-model="form.materialReceiptCode" placeholder="请输入领料单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领料单名称" prop="materialReceiptName">
              <el-input v-model="form.materialReceiptName" placeholder="请输入领料单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="需求时间" prop="demandTime">
              <el-date-picker
                v-model="form.demandTime"
                type="datetime"
                placeholder="请选择需求时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产工单" prop="workOrder">
              <el-input v-model="form.workOrder" placeholder="请输入生产工单" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作站" prop="workstation">
              <el-input v-model="form.workstation" placeholder="请输入工作站" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作站名称" prop="workstationName">
              <el-input v-model="form.workstationName" placeholder="请输入工作站名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编号" prop="clientCode">
              <el-input v-model="form.clientCode" placeholder="请输入客户编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="descs">
          <el-input
            v-model="form.descs"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete, 
  Document, 
  Tickets, 
  User, 
  Box, 
  InfoFilled, 
  Avatar,
  Close,
  Check,
  ArrowRight,
} from '@element-plus/icons-vue'
import http from '@/api/http'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const loading = ref(false)
const submitLoading = ref(false)
const total = ref(0)
const tableData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const selectedRows = ref<any[]>([])

const page = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  totalPage: 0,
})

// 查询参数
const queryParams = reactive({
  requisitionNo: '',
  requisitionName: '',
  workOrderNo: '',
  workstation: '',
  customerCode: '',
})

// 表单参数
const form = reactive({
  id: 0,
  materialReceiptCode: '',
  materialReceiptName: '',
  demandTime: '',
  workOrder: '',
  workstation: '',
  workstationName: '',
  clientCode: '',
  clientName: '',
  descs: '',
})

// 表单校验规则
const rules = reactive<FormRules>({
  requisitionNo: [
    { required: true, message: '请输入领料单编号', trigger: 'blur' }
  ],
  requisitionName: [
    { required: true, message: '请输入领料单名称', trigger: 'blur' }
  ],
  requiredTime: [
    { required: true, message: '请选择需求时间', trigger: 'change' }
  ],
  workOrderNo: [
    { required: true, message: '请输入生产工单', trigger: 'blur' }
  ],
  workstation: [
    { required: true, message: '请输入工作站', trigger: 'blur' }
  ],
  workstationName: [
    { required: true, message: '请输入工作站名称', trigger: 'blur' }
  ],
  customerCode: [
    { required: true, message: '请输入客户编号', trigger: 'blur' }
  ],
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ]
})

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:9991/api/WarehouseManagement/GetMaterialRequisitionList', {
      params:{
        pageSize:page.pageSize,
        pageIndex:page.pageIndex,
      }
    })
    tableData.value = res.data.data
    page.totalCount = res.data.totalCount
    page.totalPage = res.data.totalPage
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  page.pageIndex = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.requisitionNo = ''
  queryParams.requisitionName = ''
  queryParams.workOrderNo = ''
  queryParams.workstation = ''
  queryParams.customerCode = ''
  handleQuery()
}

// 新增按钮操作
const handleAdd = () => {
  dialogTitle.value = '新增领料单'
  resetForm()
  dialogVisible.value = true
}

// 修改按钮操作
const handleEdit = (row: any) => {
  dialogTitle.value = '修改领料单'
  resetForm()
  // 设置表单数据
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除按钮操作
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认要删除该领料单吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await http.post('/api/WarehouseManagement/DeleteMaterialRequisition', row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: 0,
    materialReceiptCode: '',
    materialReceiptName: '',
    demandTime: '',
    workOrder: '',
    workstation: '',
    workstationName: '',
    clientCode: '',
    clientName: '',
    descs: ''
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (form.id) {
          // 修改
          await http.post('/api/WarehouseManagement/UpdateMaterialRequisition', form)
          ElMessage.success('修改成功')
        } else {
          // 新增
          await http.post('/api/WarehouseManagement/CreateMaterialRequisition', form)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 表格选择项变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  page.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val: number) => {
  page.pageIndex = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .search-buttons {
        margin-left: auto;
      }
    }
  }
  
  .table-wrapper {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .left {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-form {
  .el-row {
    margin-bottom: 10px;
  }
}

.dialog-footer {
  text-align: right;
}
</style>
